package com.supersit.greensproject.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

import com.google.gson.Gson;
import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.entity.DataUpload;
import com.supersit.greensproject.resources.API;
import com.supersit.greensproject.utils.AppManager;
import com.supersit.greensproject.utils.HttpXUtils;
import com.supersit.greensproject.utils.L;
import com.supersit.greensproject.utils.MyCallBack;
import com.supersit.greensproject.utils.NetWorkInfo;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.MyTitleBar;
import com.supersit.greensproject.view.ShowDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/7/26 0026.
 */
@ContentView(R.layout.activity_data_upload_info)
public class DataUploadInfoActivity extends BaseActivity {
    private Context context;
    private MyTitleBar myTitleBar;
    @ViewInject(R.id.et_entering_data)
    private EditText etDate;
    @ViewInject(R.id.et_entering_base_name)
    private EditText etBaseName;
    @ViewInject(R.id.sp_entering_area)
    private Spinner spArea;
    @ViewInject(R.id.et_entering_base_address)
    private EditText etBaseAddress;
    @ViewInject(R.id.et_entering_contacts)
    private EditText etContacts;
    @ViewInject(R.id.et_entering_tel)
    private EditText etTel;
    @ViewInject(R.id.et_entering_output)
    private EditText etOutPut;//产量
    @ViewInject(R.id.et_entering_quarter)
    private EditText etQuarter;//季度
    @ViewInject(R.id.et_entering_proportion)
    private EditText etProportion;//面积
    @ViewInject(R.id.et_entering_next_budget)
    private EditText etNextQuarterOutput;//下季度产量
    @ViewInject(R.id.et_entering_next_date)
    private EditText etNextUploadDate;//下一次上的v的时间
    @ViewInject(R.id.btn_save_uploadinfo)
    private Button btnSave;
    private DataUpload du;
    private int merchandise;//作为种类 0蔬菜 1肉鸡 2奶牛 3塘鱼 4生猪
    private DbManager db;
    private final int UPLOAD_SUCCESS = 0x10;
    private final int UPLOAD_FAIL = 0x11;
    private final int SERVICE_ERROR = 0x12;
    private int baseId;
    private int userId;
    private ShowDialog showDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        context = this;
        setMyTitleBar();
        initVariable();
        bindListener();

    }

    private void setMyTitleBar() {
        myTitleBar = new MyTitleBar(context, findViewById(R.id.data_upload_title));
        myTitleBar.setTitleText(getResources().getString(R.string.upload_data));
        myTitleBar.setChildVisibility(false, myTitleBar.getmImgRight());
    }

    private void initVariable() {
//        ArrayAdapter quarterAdapter = ArrayAdapter.createFromResource(
//                context, R.array.quarter, R.layout.spinner_text);
//        quarterAdapter.setDropDownViewResource(R.layout.item_spinner);
//        spQuarter.setAdapter(quarterAdapter);
        ArrayAdapter AreaAdapter = ArrayAdapter.createFromResource(
                context, R.array.area, R.layout.spinner_text);
        AreaAdapter.setDropDownViewResource(R.layout.item_spinner);
        spArea.setAdapter(AreaAdapter);
        db = db = XUtilsDbManager.getInstance();
        showDialog = new ShowDialog(context);
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            du = (DataUpload) bundle.getSerializable("dataupload");
            merchandise = bundle.getInt("merchandise");
            if (null != du) {

                etDate.setText(du.getCreateDate() == null ? "" : du.getCreateDate());

                etBaseName.setText(du.getBaseName() == null ? "" : du.getBaseName());

                spArea.setSelection(du.getArea() == 0 ? 0 : du.getArea());
                spArea.setEnabled(false);
                spArea.setClickable(false);
                etBaseAddress.setText(du.getBaseAddress() == null ? "" : du.getBaseAddress());

                etContacts.setText(du.getContacts() == null ? "" : du.getContacts());

                etTel.setText(du.getTel() == null ? "" : du.getTel());

                etOutPut.setText(du.getOutput() == null ? "" : du.getOutput());//产量

                etQuarter.setText(du.getQuarter());//季度

                etProportion.setText(du.getProportion() == null ? "" : du.getProportion());//面积

                etNextQuarterOutput.setText(du.getEstimatedOutput() == null ? "" : du.getEstimatedOutput());//下季度产量

                etNextUploadDate.setText(du.getEstimatedUploadDate() == null ? "" : du.getEstimatedUploadDate());//下一次上的v的时间

            }
        }
    }

    private void bindListener() {
        myTitleBar.setImg1Listener(onClickListener);
        btnSave.setOnClickListener(onClickListener);
       // etNextUploadDate.setOnTouchListener(onTouchListener);

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.title_bar_left:
                    finish();
                    break;
                case R.id.btn_save_uploadinfo:
                    if (checkData()) {
                        String date = TextUtils.isEmpty(etDate.getText().toString()) ? "" : etDate.getText().toString().trim();
                        String baseName = TextUtils.isEmpty(etBaseName.getText().toString()) ? "" : etBaseName.getText().toString().trim();
                        int areaId = spArea.getSelectedItemPosition();
                        String baseAddress = TextUtils.isEmpty(etBaseAddress.getText().toString()) ? "" : etBaseAddress.getText().toString().trim();
                        String contacts = TextUtils.isEmpty(etContacts.getText().toString()) ? "" : etContacts.getText().toString().trim();
                        String tel = TextUtils.isEmpty(etTel.getText().toString()) ? "" : etTel.getText().toString().trim();
                        String output = TextUtils.isEmpty(etOutPut.getText().toString()) ? "" : etOutPut.getText().toString().trim();
                        String quarter = TextUtils.isEmpty(etQuarter.getText().toString()) ? "" : etQuarter.getText().toString().trim();
                        String proportion = TextUtils.isEmpty(etProportion.getText().toString()) ? "" : etProportion.getText().toString().trim();
                        String nextOutput = TextUtils.isEmpty(etNextQuarterOutput.getText().toString()) ? "" : etNextQuarterOutput.getText().toString().trim();
                        String nextDate = TextUtils.isEmpty(etNextUploadDate.getText().toString()) ? "" : etNextUploadDate.getText().toString().trim();
                        du.setCreateDate(date);
                        du.setBaseName(baseName);
                        du.setBaseAddress(baseAddress);
                        du.setArea(areaId);
                        du.setContacts(contacts);
                        du.setTel(tel);
                        du.setOutput(output);
                        du.setQuarter(quarter);
                        du.setProportion(proportion);
                        du.setEstimatedOutput(nextOutput);
                        du.setEstimatedUploadDate(nextDate);
                        du.setIsDelete(1);
                        du.setOperationsTatus(2);
                        du.setMerchandise(merchandise);
                        try {
                            if (NetWorkInfo.isNetworkAvailable(context)) {
                                //上传数据
                                dataUpload(du);
                            } else {
                                //无网络，保存本地
                                du.setIsUpload(1);
                                db.update(du);
                                clearView();
                                T.showShort(context, R.string.unnetwork_save_locality);
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                            L.d(e.getMessage().toString());
                        }
                        finish();
                    }

                    break;
            }
        }
    };

    private boolean checkData() {
        boolean flag = false;
//        if (TextUtils.isEmpty(etDate.getText().toString().trim())) {
//            T.showShort(context, R.string.maket_create_is_null);
//            return flag;
//        }
        if (TextUtils.isEmpty(etBaseName.getText().toString().trim())) {
            T.showShort(context, R.string.base_name_not_null);
            return flag;
        }
//        if (TextUtils.isEmpty(etBaseAddress.getText().toString().trim())) {
//            T.showShort(context, R.string.base_address_is_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etContacts.getText().toString().trim())) {
//            T.showShort(context, R.string.base_contacts_is_null);
//            return flag;
//        }
//        if (TextUtils.isEmpty(etTel.getText().toString().trim())) {
//            T.showShort(context, R.string.base_tel_is_null);
//            return flag;
//        }
        if (TextUtils.isEmpty(etQuarter.getText().toString().trim())) {
            T.showShort(context, R.string.update_quarter_is_null);
            return flag;
        }
        if (TextUtils.isEmpty(etOutPut.getText().toString().trim())) {
            T.showShort(context, R.string.base_output_is_null);
            return flag;
        }
//        if (TextUtils.isEmpty(etProportion.getText().toString().trim())) {
//            T.showShort(context, R.string.base_aera_is_null);
//            return flag;
//        }
        if (TextUtils.isEmpty(etNextQuarterOutput.getText().toString().trim())) {
            T.showShort(context, R.string.next_quarter_output_is_null);
            return flag;
        }
        if (TextUtils.isEmpty(etNextUploadDate.getText().toString().trim())) {
            T.showShort(context, R.string.next_upload_data_date_is_null);
            return flag;
        }
        flag = true;
        return flag;
    }

    private void clearView() {

        //  etDate.setText("");

        etBaseName.setText("");

        spArea.setSelection(0);

        etBaseAddress.setText("");

        etContacts.setText("");

        etTel.setText("");

        etOutPut.setText("");//产量

        etQuarter.setText("");//季度

        etProportion.setText("");//面积

        etNextQuarterOutput.setText("");//下季度产量

        etNextUploadDate.setText("");//下一次上的v的时间
    }

    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == KeyEvent.ACTION_DOWN) {
                Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
                DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        etNextUploadDate.setText(i + "-" + (i1 + 1) + "-" + i2);
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));
                datePickerDialog.show();
            }
            return false;
        }
    };

    /**
     * 数据上报
     */
    private void dataUpload(final DataUpload dataUpload) {
        String url = API.UploadAndUpdateUploadDada;
        Map<String, Object> map = new HashMap<>();
        Gson gson = new Gson();
        String str = gson.toJson(dataUpload);
        map.put("dataReportItem", str);
        showDialog.showLoadingDialog(getString(R.string.uploading_data));
        Callback.Cancelable cancelable = HttpXUtils.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                L.e("Request Error:" + ex.getMessage());
                showDialog.dismissLoadDialog();
                Message message = new Message();
                message.what = SERVICE_ERROR;
                handler.sendMessage(message);
            }

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                showDialog.dismissLoadDialog();
                L.d("Request result:" + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int isflog = json.optInt("isflog");//1成功  0失败
                    if (isflog == 1) {
                        int uploadDataId = json.optInt("id");
                        long timestamp = json.optLong("timestamp");
                        dataUpload.setUploadDataId(uploadDataId);
                        dataUpload.setTimeStamp(timestamp);
                        dataUpload.setIsUpload(0);//0已上传 1未上传
                        dataUpload.setOperationsTatus(-1);
                        db.update(dataUpload);
                        Message message = new Message();
                        message.what = UPLOAD_SUCCESS;
                        handler.sendMessage(message);
                    } else {
                        Message message = new Message();
                        message.what = UPLOAD_FAIL;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    showDialog.dismissLoadDialog();
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = SERVICE_ERROR;
                    handler.sendMessage(message);
                } catch (DbException e) {
                    showDialog.dismissLoadDialog();
                    Message message = new Message();
                    message.what = SERVICE_ERROR;
                    handler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        });

        System.out.print(str);
        L.d(str);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    AppManager.getAppManager().finishActivity(DataUploadInfoActivity.class);
                    T.showShort(context, R.string.save_ok);
                    break;
                case UPLOAD_FAIL:
                    T.showShort(context, R.string.save_fail);
                    break;
                case SERVICE_ERROR:
                    T.showShort(context, R.string.service_error);
                    break;
            }
        }
    };
}
